import React, { useState, useEffect, forwardRef } from "react";
import { MenuOutlined } from "@ant-design/icons";
import { Skeleton, Card, Button, Alert } from "antd";
import Dog from "@/typings/dog";
import { Link } from "react-router-dom";

import "./index.less";

interface Props {
  children?: any;
  dogs?: any;
  getDogs?: any;
  container?: any;
  currentCategory: string;
}

function DogList(props: Props, dogListRef: any) {
  const [_, forceUpdate] = useState(0);
  useEffect(() => {
    if (props.dogs.list.length === 0) {
      props.getDogs();
    }
    dogListRef.current = () => {
      forceUpdate((x) => x + 1);
    }; //提供父组件刷新接口
  }, []);

  let start = 0;
  let rem = parseInt(document.documentElement.style.fontSize); //1rem 的像素
  if (props.container.current) {
    let scrollTop = props.container.current.scrollTop; // 获取向上卷去的高度
    if (scrollTop - 7 * rem > 0) {
      // 卷去的高度减去7*rem 才是真正课程列表向上卷去的高度 一个卡片是8.67*rem
      // 7rem=header+slider+h2.lineHeight
      start = Math.floor((scrollTop - 7 * rem) / (8.67 * rem));
    }
    console.log("start-隐藏了一个卡片", start);
  }

  return (
    <section className="dog-list">
      <h2>
        <MenuOutlined />
        {props.currentCategory=="全部"?"全部品种":props.currentCategory}
      </h2>
      <Skeleton
        loading={props.dogs.list.length == 0 && props.dogs.loading}
        active
      >
        {props.dogs.list.map((dog: Dog, index: number) => {
            // 不在视口范围内用空Div代替，减少DOM重绘时间
            let showItems= props.dogs.limit;
            return  (start<showItems && index<=showItems) || (index>=start && index<start+showItems)?(
                  <Link key={dog.id} to={{pathname:`/detail/${dog.id}`,state:dog}}>
                      <Card
                      hoverable={true}
                      style={{width:"100%"}}
                      cover={<img alt={dog.title} src={dog.poster} />}
                      >
                          <Card.Meta
                          title={dog.title}
                          description={`价格:¥${dog.price}元`}
                          />
                      </Card>
                  </Link>                 
              ):(
                  <div key={index} style={{height:`${8.6666667*rem}px`}}></div>
              )
        })}
        {props.dogs.hasMore ? (
          <Button
            onClick={props.getDogs}
            loading={props.dogs.loading}
            type="primary"
            block
          >
            {props.dogs.loading ? "" : "加载更多"}
          </Button>
        ) : (
          <Alert
            style={{ textAlign: "center" }}
            message="到底了"
            type="warning"
          ></Alert>
        )}
      </Skeleton>
    </section>
  );
}

export default forwardRef(DogList);
